//
//  MenuViewController.m
//  BookRank
//
//  Created by wststar on 13-10-20.
//  Copyright (c) 2013年 wststar. All rights reserved.
//

#import "MenuViewController.h"
#import "HomeViewController.h"
#import "MessageViewController.h"
#import "ProfileViewController.h"
#import "DiscoverViewController.h"
#import "MoreViewController.h"
#import "BaseNavigationController.h"
#import "DDMenuController.h"
#import "LeftViewController.h"
#import "RightViewController.h"
#import "UIFactory.h"
#import "AppDelegate.h"

#import "ThemeButton.h"

@interface MenuViewController ()

@end

@implementation MenuViewController
@synthesize menuController;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)timerAction:(NSTimer *)timer{
    [self loadUnreadData];
}

-(void)refreshUnReadView:(NSDictionary *)result{
    //新微博未读数
    NSNumber * status = [result objectForKey:@"status"];
    if (_badgeView == nil) {
        _badgeView = [UIFactory createImageView:@"main_badge.png"];
        _badgeView.frame = CGRectMake(64-25, 5, 20, 20);
        [_tabBarView addSubview:_badgeView];
        
        UILabel * label = [[[UILabel alloc]initWithFrame:_badgeView.bounds]autorelease];
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont boldSystemFontOfSize:13.0f];
        label.textColor =[UIColor purpleColor];
        label.tag = 100;
        [_badgeView addSubview:label];
    }
    if (status.intValue > 0) {
        UILabel * labelView = (UILabel *)[_badgeView viewWithTag:100];
        labelView.text = [NSString stringWithFormat:@"%@",status];
        _badgeView.hidden = NO;
    }else{
        _badgeView.hidden = YES;
    }
}

#pragma mark -loadData
-(void)loadUnreadData{
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    SinaWeibo * sinaweibo = appDelegate.sinaweibo;
    [sinaweibo requestWithURL:@"remind/unread_count.json" params:nil httpMethod:@"GET" block:^(NSDictionary * result) {
        [self refreshUnReadView:result];
    }];
}

-(void)showBadge:(BOOL)show{
    _badgeView.hidden = !show;
}

#pragma mark --UI
//单独对首页最处理 因为只有首页才有滑动菜单 不做成全局的
- (void)createDDMenuControllerOnView:(HomeViewController *)home
{
    BaseNavigationController * nav = [[BaseNavigationController alloc]initWithRootViewController:home];
    menuController = [[DDMenuController alloc]initWithRootViewController:nav];
    menuController.tabBarItem = home.tabBarItem;
    
    LeftViewController * left = [[LeftViewController alloc]init];
    RightViewController * right = [[RightViewController alloc]init];
    [menuController setLeftViewController:left];
    [menuController setRightViewController:right];
    //return menu;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    _homeViewController = [[[HomeViewController alloc]init] autorelease];
    
    MessageViewController *message = [[[MessageViewController alloc]init] autorelease];
    ProfileViewController *profile = [[[ProfileViewController alloc]init] autorelease];
    DiscoverViewController * discover = [[[DiscoverViewController alloc]init]autorelease];
    MoreViewController *more = [[[MoreViewController alloc]init] autorelease];
    
    [self createDDMenuControllerOnView:_homeViewController];

    //处理余下的几个Tab
    NSArray * views = @[message,profile,discover,more];
    NSMutableArray * viewControllers = [NSMutableArray arrayWithObject:menuController];
    for (UIViewController * viewController in views) {
        BaseNavigationController * nav = [[BaseNavigationController alloc]initWithRootViewController:viewController];
        [viewControllers addObject:nav];
        [nav release];
    }
    //设置views
    self.viewControllers = viewControllers;
    //自定义tabbar按钮 2013-10-26 18:44
    [self initTabBarView];
    
    //每个60s 请求一次未读的消息数目
    [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    
}


-(void)initTabBarView{
    //UIScreen mainScreen].bounds.size.height;
    _tabBarView = [[[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight-49, ScreenWidth, 49)]autorelease];
   // _tabBarView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"tabbar_background.png"]];
    
    UIImageView *tabBarGroundView = [UIFactory createImageView:@"tabbar_background.png"];
    tabBarGroundView.frame = _tabBarView.bounds;
    [_tabBarView addSubview:tabBarGroundView];
    
    [self.view addSubview:_tabBarView];
    NSArray * background = @[@"tabbar_home.png",@"tabbar_message_center.png",@"tabbar_profile.png",@"tabbar_discover.png",@"tabbar_more.png"];
    NSArray * hightbackground = @[@"tabbar_home_highlighted.png",@"tabbar_message_center_highlighted.png",@"tabbar_profile_highlighted.png",
                                  @"tabbar_discover_highlighted.png",@"tabbar_more_highlighted.png"];
    for (int i = 0 ; i <background.count; i ++) {
        NSString * backImageName = background[i];
        NSString * hightImageName = hightbackground[i];
        //UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        UIButton * button = [UIFactory createButton:backImageName highlighted:hightImageName];
        button.showsTouchWhenHighlighted = YES;
        button.frame = CGRectMake((64-30)/2+(i*64),(49-30)/2, 30, 30);
        button.tag = i;
        //[button setBackgroundImage:[UIImage imageNamed:backImageName] forState:UIControlStateNormal];
        //[button setBackgroundImage:[UIImage imageNamed:hightImageName] forState:UIControlStateHighlighted];
        [button addTarget:self action:@selector(selectedTab:) forControlEvents:UIControlEventTouchUpInside];
        [_tabBarView addSubview:button];
    }
    
    //设置tab下面的滑动线
    _sliderView = [UIFactory createImageView:@"tabbar_slider.png"];
    _sliderView.backgroundColor = [UIColor clearColor];
    _sliderView.frame = CGRectMake((64-15)/2, 5, 15, 44);
    [_tabBarView addSubview:_sliderView];
    
}

-(void)selectedTab:(UIButton *)button{
    //NSLog(@"%d,%d",self.selectedIndex,button.tag);
    
    //滑动
    float x = button.left +(button.width-_sliderView.width)/2;
    [UIView animateWithDuration:0.2 animations:^{
        _sliderView.left = x;
    }];

    //判断是否重复点击home图标
    if (self.selectedIndex == button.tag && button.tag == 0) {
        [_homeViewController refreshWeibo];
    }
    
    self.selectedIndex = button.tag;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -SinaWeiboDelegate
- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweibo {
    //保存认证的数据到本地
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              sinaweibo.accessToken, @"AccessTokenKey",
                              sinaweibo.expirationDate, @"ExpirationDateKey",
                              sinaweibo.userID, @"UserIDKey",
                              sinaweibo.refreshToken, @"refresh_token", nil];
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)sinaweiboDidLogOut:(SinaWeibo *)sinaweibo {
    //移除认证的数据
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SinaWeiboAuthData"];
}

@end
